<template>
    <div class="uploadImg">
        <p>{{title}}</p>
        <div class="moveImg">
            <el-upload 
            :action="action"
            :file="title" :file-list="initLists" :limit="limit" list-type="picture-card" :on-remove="handleRemove" :before-upload="beforeAvatarUpload" :on-success="handleAvatarSuccess">
                <i class="el-icon-plus" />
            </el-upload>
        </div>
    </div>
</template>

<script>
export default {
    props:{
        value:'',
        title:String,
        limit:Number
    },
    data(){
        return{
           initLists:[],
           imageUrl:[],
           action:''
        }
    },
    created(){
        this.action = `${process.env.NODE_ENV=='development'?'/fileApi':''}/resource/fileupload/upload`
        this.init(this.value)
    },
    methods:{
        init(data=[]){
            if(!data || data.length<1) return
            this.imageUrl = data
            data.forEach(item =>{
                this.initLists.push({url:item})
            })
        },
        handleRemove(file, fileList) {
            let arr = []
            console.log("2-fileList:",fileList)
            fileList.forEach(item =>{
                if(item.response){
                   arr.push(item.response.url) 
                }else{
                    arr.push(item.url)
                }  
            })
            this.imageUrl = arr
            this.$emit('input',arr)
        },
        beforeAvatarUpload(file) {
            const isPic = (file.type === 'image/jpeg') || (file.type === 'image/jpg') || (file.type === 'image/png')
            const isLt2M = file.size / 1024 / 1024 < 3
            if (!isPic) {
                this.$message.error('请上传格式为JPG, JPEG, PNG的图片')
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 3MB!')
            }
            return isPic && isLt2M
        },
        handleAvatarSuccess(res) {
            if (res.success) {
                //this.imageUrl.push(res.url)
                this.imageUrl.push(res.url)
                this.$emit('input',this.imageUrl)
            } else {
                this.$message({
                    message: res.message,
                    type: 'error'
                })
            }
        },
    }
}
</script>

<style lang="scss" scoped>
    .uploadImg {
        p {
            margin: 0;
            padding: 0;
            color: #ccc;
            padding-bottom: 10px;
        }
    }
</style>